import { Button, Upload, Tag, Toast } from "@douyinfe/semi-ui";
import { AfterUploadProps, FileItem, OnChangeProps } from "@douyinfe/semi-ui/lib/es/upload";
import PdfInvoiceResult from "../models/PdfInvoiceResult.ts";
import { useMemo, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import store from "../models/store.ts";

const C = () => {
    const [files, setFiles] = useState<FileItem[]>(store?.files ?? []);
    const pdfResultsLength = useMemo(() => store.pdfSuccessResults.length, [store.pdfSuccessResults]);
    const navigate = useNavigate();


    function onChange(props: OnChangeProps) {
        const { fileList } = props;
        setFiles([...fileList]);
        store.files = fileList;
    }


    function afterUpload(props: AfterUploadProps) {
        const { response, file } = props;
        const ret = response as PdfInvoiceResult
        // 可以根据业务接口返回，决定当次上传是否成功
        if (ret.success) {
            return {
                autoRemove: false,
                validateMessage: <Tag color="green" type="solid" >处理成功 </Tag >,
                status: 'uploadSuccess',
                name: file.name
            }
        }
        return {
            autoRemove: false,
            status: 'uploadFail',
            validateMessage: <Tag color="pink" >{`无法解析发票`} </Tag >,
            name: file.name,
        }
    }

    function onClick() {
        if (store.pdfSuccessResults.length === 0) {
            return Toast.error('没有可用的发票文件')
        }
        navigate('/download')
    }

    return <>
        <Upload action={"/invoice/extract"}
                draggable={true}
                name={'file'}
                fileList={files}
                onChange={onChange}
                afterUpload={afterUpload}
                dragMainText={'点击上传PDF发票文件或拖拽文件到这里'}
                dragSubText="可多选，可追加，仅支持标准PDF发票文件"
                multiple={true}
                accept={'.pdf'} >
        </Upload >
        <div style={{ display: 'flex', justifyContent: 'flex-end' }} >
            {pdfResultsLength ?
                <Button
                    onClick={onClick}
                    style={{ width: '120px', marginTop: '20px', height: '40px' }}
                    size={'large'}
                    type="primary"
                    theme="solid"
                >下一步</Button >
                : null}
        </div >
    </>
}
export default C;